// 包含n个action create
import {
  reqRegister,
  reqLogin,
  reqUpdate,
  reqUser,
  reqUserList,
  reqChatMsgList,
  reqReadMsg
} from '../api/index'
import {
  AUTH_SUCCESS,
  ERROR_MSG,
  RECEIVE_USER,
  RESET_USER,
  RECEIVE_USER_LIST,
  RECEIVE_MSG_LIST,
  RECEIVE_MSG,
  MSG_READ
} from './action-type'
import { Toast } from 'antd-mobile'
import io from 'socket.io-client'
// 授权成功的同步action
const auth_success = user => ({ type: AUTH_SUCCESS, data: user })
// 错误提示信息的同步action
const error_msg = msg => ({ type: ERROR_MSG, data: msg })
// 接收用户的同步action
const receice_user = user => ({ type: RECEIVE_USER, data: user })
// 重置用户的同步action
export const reset_user = msg => ({ type: RESET_USER, data: msg })
// 接收用户列表的同步action
const receice_user_list = userList => ({
  type: RECEIVE_USER_LIST,
  data: userList
})
// 接收一个消息的同步action
const receive_msg = (chatMsg, userId) => ({
  type: RECEIVE_MSG,
  data: { chatMsg, userId }
})

// 接收消息列表的同步action
const receive_msg_list = ({ users, chatMsgs, userId }) => ({
  type: RECEIVE_MSG_LIST,
  data: { users, chatMsgs, userId }
})

// 读取某个聊天的同步action
const msg_read = ({ count, from, to }) => ({
  type: MSG_READ,
  data: { count, from, to }
})
/**
 * 单例对象
 * 1. 创建对象之前：判断对象是否已经存在，只有不存在时才创建
 * 2. 创建对象之后：保存对象
 *
 */
function InitIO(dispatch, userId) {
  if (!io.socket) {
    // 连接服务器 得到与服务器的链接对象
    io.socket = io('ws://localhost:4000')
    // 绑定监听，接收服务器发送的消息
  }
  io.socket.on('receiveMsg', function(chatMsg) {
    console.log('客户端接收服务器发送的消息', chatMsg)
    // 只有当chatMsg是与当前用户相关的消息，才会分发同步action保存
    if (chatMsg.to === userId || chatMsg.from === userId) {
      dispatch(receive_msg(chatMsg, userId))
    }
  })
}

// 异步获取消息列表数据
async function getMsgList(dispatch, userId) {
  InitIO(dispatch, userId)
  const responce = await reqChatMsgList()
  const result = responce.data
  if (result.code === 0) {
    const { users, chatMsgs } = result.data
    // 分发action
    dispatch(receive_msg_list({ users, chatMsgs, userId }))
  }
}

// 读取消息的异步action
export const readMsg = (targetId, userId) => {
  return async dispatch => {
    const responce = await reqReadMsg(targetId)
    const result = responce.data
    if (result.code === 0) {
      // const count = result.data
      // const from = targetId
      // const to = userId
      // dispatch(msg_read({ count, from, to }))
      const responce = await reqChatMsgList()
      const result = responce.data
      if (result.code === 0) {
        const { users, chatMsgs } = result.data
        // 分发action
        dispatch(receive_msg_list({ users, chatMsgs, userId }))
      }
    }
  }
}

// 发送消息的异步action
export const sendMSG = ({ from, to, content }) => {
  return dispatch => {
    console.log('向服务器发送消息', { from, to, content })
    io.socket.emit('sendMSG', { from, to, content })
  }
}

// 注册
export const register = user => {
  const { password, username, password2, type } = user
  // 表单的前台验证
  if (password !== password2) {
    return error_msg('2次密码必须一致')
  }
  if (!username) {
    return error_msg('用户名不能为空')
  }
  if (!password || !password2) {
    return error_msg('密码不能为空')
  }
  return async dispatch => {
    // 发送注册的异步请求
    const response = await reqRegister({ password, username, type })
    const result = response.data
    if (result.code === 0) {
      //成功
      getMsgList(dispatch, result.data._id)
      Toast.success('注册成功', 1)
      dispatch(auth_success(result.data))
    } else {
      // 失败
      Toast.fail('注册失败', 1)
      dispatch(error_msg(result.msg))
    }
  }
}

// 登录
export const login = user => {
  const { password, username } = user
  // 表单的前台验证
  if (!username) {
    return error_msg('用户名不能为空')
  }
  if (!password) {
    return error_msg('密码不能为空')
  }
  return async dispatch => {
    // 发送注册的异步请求
    const response = await reqLogin(user)
    const result = response.data
    if (result.code === 0) {
      //成功
      getMsgList(dispatch, result.data._id)
      Toast.success('登录成功', 1)
      dispatch(auth_success(result.data))
    } else {
      // 失败
      Toast.fail('登录失败', 1)
      dispatch(error_msg(result.msg))
    }
  }
}

// 更新用户信息的异步action
export const updateUser = user => {
  return async dispatch => {
    const response = await reqUpdate(user)
    const result = response.data
    if (result.code === 0) {
      // 更新成功 data
      Toast.success('保存成功', 1)
      dispatch(receice_user(result.data))
    } else {
      // 更新失败 msg
      dispatch(reset_user(result.msg))
    }
  }
}

// 获取用户的异步action
export const getUser = () => {
  return async dispatch => {
    const responce = await reqUser()
    const result = responce.data
    if (result.code === 0) {
      getMsgList(dispatch, result.data._id)
      dispatch(receice_user(result.data))
    } else {
      dispatch(receice_user(result.msg))
    }
  }
}

// 获取用户列表的异步action
export const getUserList = type => {
  return async dispatch => {
    const responce = await reqUserList(type)
    const result = responce.data
    if (result.code === 0) {
      dispatch(receice_user_list(result.data))
    }
  }
}
